package cn.geapi.core.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import cn.geapi.core.util.security.HashIdContext;
import cn.geapi.core.util.security.annotation.Hashable;

public class EntityBeanConvert {
	/**
	 * bean转换，同时对id进行编码
	 * 
	 * @param source
	 * @param distClazz
	 * @return
	 * @throws Exception
	 */
	public static <T> T convert(Object source, Class<T> distClazz)
			throws Exception {
		if (null == source)
			return null;
		T dist = distClazz.newInstance();
		BeanUtils.copyProperties(dist, source);
		Field fields[] = distClazz.getDeclaredFields();
		Method method = null;
		Hashable hashable = null;
		PropertyDescriptor descriptor = null;
		Object value = null;
		for (Field field : fields) {
			if (field.getName().equals("serialVersionUID"))
				continue;
			descriptor = new PropertyDescriptor(field.getName(), distClazz);
			method = PropertyUtils.getReadMethod(descriptor);
			hashable = method.getAnnotation(Hashable.class);
			if (null != hashable) {
				value = method.invoke(dist);
				PropertyUtils.getWriteMethod(descriptor).invoke(
						dist,
						HashIdContext.getHashIdStrategy(hashable.idType())
								.encrypt(
										Long.valueOf(String.valueOf(value))
												.longValue()));
			}
		}
		return dist;
	}
}
